﻿using AppEvents.JsonModel;
using MebApp.Launcher.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MebApp.Launcher
{
    public class AppInstaller2
    {
        public static EventHandler<AppInstallation> AppInstallCompleted;
        static List<AppInstallation> AppInstalls = new List<AppInstallation>();
        public static AppState GetAppState(Guid id)
        {
            lock (AppInstalls)
            {
                var app = AppInstalls.Find(x => x.AppId == id);
                if (app != null)
                    return app.AppState;
            }
            return AppState.None;
        }
        public static void SetAppState(Guid id, AppState state)
        {
            lock (AppInstalls)
            {
                var appIdx = AppInstalls.FindIndex(x => x.AppId == id);
                if (appIdx == -1)
                    AppInstalls.Add(new AppInstallation { AppId = id, AppState = state });
                else
                    AppInstalls[appIdx].AppState = state;
            }
        }

        /// <summary>
        /// 执行本安装前，先将下载的update.xml拷贝到安装目录
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="installPath"></param>
        public static void RunInstall(AppJson info, string sid, string installPath, Action<AppJson, AppState> callback)
        {
            var state = GetAppState(info.ID);
            if (state == AppState.Installing)
            {
                MessageBox.Show("正在安装请稍后...");
                return;
            }
            var appJsonFile = Path.Combine(installPath, "app.json");
            if (!File.Exists(appJsonFile))
            {
                MessageBox.Show("没有找到安装必须的app.json文件");
                return;
            }
            new Thread(() =>
            {
                SetAppState(info.ID, AppState.Installing);
                var process = new Process();
                process.StartInfo = new ProcessStartInfo();
                process.StartInfo.WorkingDirectory = installPath;
                process.StartInfo.FileName = Path.Combine(Application.StartupPath, "MebAppInstaller.exe");
                process.StartInfo.Arguments = info.ID + " " + info.Version + " " + sid + " " + LauncherApp.AppClient.BaseUrl;
                process.Start();
                process.WaitForExit();
                if (process.ExitCode != 0)
                {
                    SetAppState(info.ID, AppState.None);
                    MessageBox.Show($"商店应用在安装出错，错误代码 {process.ExitCode}");
                }
                else
                {
                    AppInstaller.AddInstalled(info, installPath);
                    LauncherApp.AppClient.AddAppInstall(info.ID);
                    SetAppState(info.ID, AppState.Installed);
                }
                callback(info, GetAppState(info.ID));
            }).Start();
        }
    }
    public enum AppState
    {
        None,
        Installing,
        Installed
    }
}
